from sqlalchemy.orm import Session
from models.schedule import Schedule
from typing import List, Optional
from datetime import datetime


class ScheduleDAO:
    @staticmethod
    def create_schedule(
        db: Session,
        user_id: int,
        title: str,
        start_time: datetime,
        end_time: Optional[datetime] = None,
        reminder_at: Optional[datetime] = None,
        notes: Optional[str] = None
    ) -> Schedule:
        schedule = Schedule(
            user_id=user_id,
            title=title,
            start_time=start_time,
            end_time=end_time,
            reminder_at=reminder_at,
            notes=notes
        )
        db.add(schedule)
        db.commit()
        db.refresh(schedule)
        return schedule

    @staticmethod
    def get_schedule_by_id(db: Session, schedule_id: int) -> Optional[Schedule]:
        return db.query(Schedule).filter(Schedule.id == schedule_id).first()

    @staticmethod
    def get_user_schedules(db: Session, user_id: int) -> List[Schedule]:
        return db.query(Schedule).filter(Schedule.user_id == user_id).order_by(Schedule.start_time).all()

    @staticmethod
    def update_schedule(
        db: Session,
        schedule_id: int,
        title: Optional[str] = None,
        start_time: Optional[datetime] = None,
        end_time: Optional[datetime] = None,
        reminder_at: Optional[datetime] = None,
        notes: Optional[str] = None
    ) -> Optional[Schedule]:
        schedule = db.query(Schedule).filter(Schedule.id == schedule_id).first()
        if not schedule:
            return None
        if title is not None:
            schedule.title = title
        if start_time is not None:
            schedule.start_time = start_time
        if end_time is not None:
            schedule.end_time = end_time
        if reminder_at is not None:
            schedule.reminder_at = reminder_at
        if notes is not None:
            schedule.notes = notes
        db.commit()
        db.refresh(schedule)
        return schedule

    @staticmethod
    def delete_schedule(db: Session, schedule_id: int) -> bool:
        schedule = db.query(Schedule).filter(Schedule.id == schedule_id).first()
        if not schedule:
            return False
        db.delete(schedule)
        db.commit()
        return True
